import { Injectable, Component, OnInit, TemplateRef } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';

import 'rxjs/add/operator/switchMap';
import { Observable } from 'rxjs/Observable';

import { Hero } from '../../../domain/entities';
import { HeroService } from '../hero.service';

import { BsModalService } from 'ngx-bootstrap/modal';
import { BsModalRef } from 'ngx-bootstrap/modal/modal-options.class';

import { ConfirmComponent } from '../../../shared/modal/confirm/confirm.component';

@Component({
  selector: 'app-hero-list',
  templateUrl: './hero-list.component.html',
  styleUrls: ['./hero-list.component.css']
})

@Injectable()
export class HeroListComponent implements OnInit {
  public modalRef: BsModalRef;
  public bsModalRef: BsModalRef;
  heroes: Hero[];
  imgSrc: string;

  constructor(
    private modalService: BsModalService,
    private service: HeroService,
    private route: ActivatedRoute,
    private router: Router) {
    this.imgSrc = 'assets/add.png';
  }

  public openModal(template: TemplateRef<any>, title: string) {
    console.log(title);
    this.modalRef = this.modalService.show(template);
  }

  public openModalWithComponent(name: string) {
    const list = ['Open a modal with component', 'Pass your data', 'Do something else', '...'];
    this.bsModalRef = this.modalService.show(ConfirmComponent);
    this.bsModalRef.content.title = 'Modal with component';
    this.bsModalRef.content.list = list;
    setTimeout(() => {
      list.push('PROFIT==>' + name);
    }, 2000);
  }

  ngOnInit() {
    // this.heroes = this.service.getHeroes();
    // this.heroes = this.route.params
    //   .switchMap((params: Params) => {
    //     this.selectedId = +params['id'];
    //     return this.service.getHeroes();
    //   });
    this.getHeroes();
  }


  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    return Promise.reject(error.message || error);
  }

  getHeroes() {
    this.service.getHeroes()
      .then(data => this.heroes = data)
      .catch(this.handleError);

  }

  onSelect(hero: Hero): void {
    console.log(hero.name);
    this.router.navigate(['/hero', hero.id]);
  }

  onAdd(): void {
    console.log('add clicked.')
    this.router.navigate(['/heroes/add']);
  }

  onDelete(id: number): void {
    console.log('hero' + id + 'delete');
    this.service.delete(id)
      .then(data => {
        console.log(data);
        this.getHeroes();
      })
      .catch(this.handleError);

  }
}


